package com.cml.infrastructure;

import com.cml.common.constant.NodeStatus;
import com.cml.common.context.ServerContext;
import com.cml.domain.entity.Message;
import com.cml.domain.entity.ServerNode;
import com.cml.domain.factory.MessageBuilderFactory;
import com.cml.domain.service.ServerNodeHAManagerService;
import org.apache.log4j.Logger;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingQueue;

/**
 * 姓名：陈茂林
 * 时间：2023/10/7 16:19
 * 描述：
 */
public class ServerWriteIoThread extends Thread{
    private Socket socket;

    private DataOutputStream dataOutputStream;
    private BlockingQueue<Message> blockingQueue;

    private ServerNode remoteServerNode;

    private  ServerContext serverContext;

    private IOThreadRunningSignal ioThreadRunningSignal;
    Logger logger = Logger.getLogger(ServerWriteIoThread.class);
    public ServerWriteIoThread(IOThreadRunningSignal ioThreadRunningSignal,ServerContext serverContext, ServerNode remoteServerNode, Socket socket, BlockingQueue blockingQueue) throws IOException {
        this.socket = socket;
        this.blockingQueue = blockingQueue;
        this.dataOutputStream= new DataOutputStream(socket.getOutputStream());
        this.serverContext = serverContext;
        this.remoteServerNode=remoteServerNode;
        this.ioThreadRunningSignal=ioThreadRunningSignal;
    }

    @Override
    public void run() {
        while (NodeStatus.getInstance().isRunning() && ioThreadRunningSignal.isRunning()){
            try {
                Message message = blockingQueue.take();
                ByteBuffer byteBuffer = MessageBuilderFactory.buildByteBuffer(message);
                this.dataOutputStream.write(byteBuffer.array());
                this.dataOutputStream.flush();
               // logger.info("发送消息到"+socket.getRemoteSocketAddress()+",发送量为："+byteBuffer.capacity());
            } catch (Exception e) {
                logger.error(e);
                ServerNodeHAManagerService.getInstance(serverContext).ha(remoteServerNode);
                ioThreadRunningSignal.setIsRunning(false);
            }
        }
    }
}
